package com.yanx.framework.advice;

import com.yanx.common.result.IResult;
import com.yanx.common.utils.Json_;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Order(0)
@ControllerAdvice
public class StringResponseBodyAdvice extends BaseResponseBodyAdvice implements ResponseBodyAdvice<String> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return isStringConverter(converterType) && isApiResult(returnType);
    }

    @Override
    public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        IResult result = createApiResult(returnType);
        result.initData(body);
        return Json_.toJson(result);
    }

}
